<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\ConfigEnum;
use app\enum\KuaiShouEnum;
use app\service\batch\KuaiShouBatchService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Cache;

class KsBatchProjectCreativeMaterialWork extends BaseWork
{
    public const REDIS_TASK_KEY = ConfigEnum::CACHE_CONFIG[KuaiShouEnum::BATCH_CONFIG_KEY]['batch_material'];

    protected function configure()
    {
        // 指令配置
        $this->setName('ks_batch_project_creative_material_work');
        // 设置参数
        $this->setDescription('快手智能化搭建处理创意结构体素材')
            ->addArgument('sort', Argument::OPTIONAL, '拿队列顺序');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('=======快手智能化搭建处理创意结构体素材开始' . date('Y-m-d H:i:s', time()) . '=======');
        try {
            $sort = intval($input->getArgument('sort'));
            $redis = Cache::store('redis')->handler();
            $st = time() + 5 * 60;
            while (time() < $st) {
                if ($sort == 1) {
                    // 倒叙
                    $id = $redis->rPop(self::REDIS_TASK_KEY);
                } else {
                    $id = $redis->lPop(self::REDIS_TASK_KEY);
                }
                if (! $id) {
                    usleep(500000);
                    continue;
                }
                $res = KuaiShouBatchService::batchCreateCreativeContent(intval($id));
                if (! $res) {
                    $output->writeln('=======失败,content_id:' . $id . KuaiShouBatchService::getError(0) . date('Y-m-d H:i:s', time()) . '=======');
                }
            }
        } catch (\Exception $e) {
            dump($e);
        }
        $output->writeln('=======快手智能化搭建处理创意结构体素材结束' . date('Y-m-d H:i:s', time()) . '=======');
    }
}
